package cn.com.openportal.ffw.common.utils;

import cn.com.openportal.ffw.common.xss.SQLFilter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 查询参数
 *
 * @author LeeSon
 */
public abstract class BaseQuery<T> {
    private static Logger logger = LoggerFactory.getLogger(BaseQuery.class);

    public IPage<T> getPage(Map<String, Object> params) {
        return this.getPage(params, null, false);
    }

    public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
        //分页参数
        long curPage = 1;
        long limit = 10;

        if (params.get(Constant.PAGE) != null) {
            curPage = Long.parseLong((String) params.get(Constant.PAGE));
        }
        if (params.get(Constant.LIMIT) != null) {
            limit = Long.parseLong((String) params.get(Constant.LIMIT));
        }

        //分页对象
        Page<T> page = new Page<>(curPage, limit);

        //自定义排序字段
        page=getQueryOrderBy(params,page);

        //分页参数
        params.put(Constant.PAGE, page);

        //排序字段
        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String orderField = SQLFilter.sqlInject((String) params.get(Constant.ORDER_FIELD));
        String order = (String) params.get(Constant.ORDER);


        //前端字段排序
        if (StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)) {
            if (Constant.ASC.equalsIgnoreCase(order)) {
                return page.addOrder(OrderItem.asc(orderField));
            } else {
                return page.addOrder(OrderItem.desc(orderField));
            }
        }

        //没有排序字段，则不排序
        if (StringUtils.isBlank(defaultOrderField)) {
            return page;
        }

        //默认排序
        if (isAsc) {
            page.addOrder(OrderItem.asc(defaultOrderField));
        } else {
            page.addOrder(OrderItem.desc(defaultOrderField));
        }

        return page;
    }

    private Page<T> getQueryOrderBy(Map<String, Object> params, Page<T> page) {
        try {
            Class<?> clazz = GenericSuperclassUtil.getActualTypeArgument(this.getClass());
            Field[] fs = clazz.getDeclaredFields();
            for (int i = 0; i < fs.length; i++) {
                String fieldName = fs[i].getName();
                if (StringUtils.isBlank(fieldName)) {
                    continue;
                }
                String order = (String) params.get(fieldName + Constant.ORDER_BY);
                if (StringUtils.isBlank(order)) {
                    continue;
                }
                //前端字段排序
                if (Constant.ASC.equalsIgnoreCase(order)) {
                    page.addOrder(OrderItem.asc(fieldName));
                } else {
                    page.addOrder(OrderItem.desc(fieldName));
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return page;
    }
}
